import React from 'react';
import './goodsrelevance.less';
import { Layout, Breadcrumb, Icon, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import { Link, hashHistory } from 'react-router';

const FormItem = Form.Item;
const config = new Config()
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const { TextArea } = Input;
const token = sessionStorage.getItem('token')

class RegForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pagesize: 12,// 每页显示的页数
            pageindex: 1,//this.props.location.state == undefined ? 1 : Number(this.props.location.state.pageindex),// 当前页
            relationname: '',//关联名
            relationstatus: undefined,//状态
            relationlist: [],//关联列表数据
            relationcount: 0,//关联列表总数
            Closevisible: false, //关闭，弹出框
            OperationRelationID: 0,//操作关联ID
            OperationStatus: '',//操作关联状态
            OperationRelationName: '',//操作关联名称
            ClosevisibleDel: false,//删除对话框
        }
    }

    componentDidMount() {
        this.GetProductRelationList();
    }
    //商品关联列表
    GetProductRelationList() {
        $.ajax({
            url: `${config.JuseProduct}/relations/list`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                relationName: this.state.relationname,
                state: this.state.relationstatus,
            },
            success: res => {
                console.log('商品关联列表', res)
                if (res.code === 200) {
                    console.log(res)
                    this.setState({
                        relationlist: res.data.rows,
                        relationcount: res.data.count,
                    });
                } else {
                    message.config({
                        top: 50,
                    });
                    message.error('商品关联列表加载失败，请返回重新操作', 2);
                }
            }
        });
    }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.GetProductRelationList();
        });
    }
    //状态改变事件
    relationstatusChange(v) {
        this.setState({
            relationstatus: v
        });
    }
    //搜索
    searchBtn() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                const form = this.props.form;
                this.setState({
                    relationname: form.getFieldValue('txt_RelationName') ? form.getFieldValue('txt_RelationName') : '',
                    pageindex: 1,
                }, () => {
                    this.GetProductRelationList();
                });
            }
        });
    }
    //重置
    resetBtn() {
        const form = this.props.form;
        form.setFieldsValue({ txt_RelationName: "" });
        this.setState({
            relationstatus: undefined,
            pageindex: 1,
            relationname: undefined
        }, () => {
            this.GetProductRelationList();
        });
    }


    //关闭/启用标签对话框
    CloseshowModal(relationid, relationstatus, relationname) {
        this.setState({
            OperationRelationID: relationid,
            OperationStatus: relationstatus,
            OperationRelationName: relationname,
            Closevisible: true,
        });
    }
    //确定启用/关闭关联
    ClosehandleOk(relationid, relationstatus, relationname) {
        if (relationstatus === 0) { // 启用
            $.ajax({
                url: `${config.JuseProduct}/relations/use`,
                type: 'post',
                headers: {
                    'Authorization': 'Bearer ' + token,
                },
                data: {
                    relationId: relationid,
                },
                success: res => {
                    console.log('启用', res)
                    if (res.code === 200) {
                        this.setState({
                            Closevisible: false,
                        }, () => {
                            this.GetProductRelationList();
                        });
                    }
                }
            })
        } else { // 关闭
            $.ajax({
                url: `${config.JuseProduct}/relations/stop`,
                type: 'post',
                headers: {
                    'Authorization': 'Bearer ' + token,
                },
                data: {
                    relationId: relationid,
                },
                success: res => {
                    console.log('关闭', res)
                    if (res.code === 200) {
                        this.setState({
                            Closevisible: false,
                        }, () => {
                            this.GetProductRelationList();
                        });
                    }
                }
            })
        }
    }
    //取消确定启用/关闭关联
    ClosehandleCancel() {
        this.setState({
            Closevisible: false,
        });
    }

    //删除关联
    DeleteProductRelation(relationid) {
        this.setState({
            OperationRelationID: relationid,
            ClosevisibleDel: true,
        });
    }

    //取消删除对话框
    ClosehandleDelCancel() {
        this.setState({
            ClosevisibleDel: false,
        });
    }

    //确定删除
    ClosehandleDelOk(relationid) {
        $.ajax({
            url: `${config.JuseProduct}/relations/delete`,
            type: "post",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                relationId: relationid
            },
            async: true,
            success: res => {
                if (res.code === 200) {
                    message.success(`关联删除成功！`);
                    this.setState({
                        ClosevisibleDel: false
                    }, () => this.GetProductRelationList());
                } else {
                    message.error(`删除失败，请重新操作`, 2);
                }
            }
        });
    }

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;

        const columns = [{
            title: '序号',
            dataIndex: 'key',
        }, {
            title: '关联名称',
            dataIndex: 'relationName',
        }, {
            title: '关联数量',
            dataIndex: 'useCount',
        }, {
            title: '状态',
            dataIndex: 'state',
            render: text => text === 1 ? "启用" : "禁用",
        }, {
            title: '操作',
            dataIndex: '',
            render: (text, record) => {
                return <div>
                    <Link to={"/relationdetail/" + record.relationId + "&" + record.relationName + "&" + record.state + "&" + this.state.pageindex}><Icon type="edit" /></Link>&nbsp;&nbsp;
                    <a onClick={this.CloseshowModal.bind(this, record.relationId, record.state, record.relationName)}>{record.state === 0 ? "启用" : "关闭"}</a>
                    &nbsp;&nbsp;<a onClick={this.DeleteProductRelation.bind(this, record.relationId)}><Icon type="delete" /></a>
                </div>;
            }
        }];

        let dataList = this.state.relationlist.map((item, i) => {
            item.key = i + 1
            return item
        });

        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                                <Breadcrumb.Item>商品关联管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_RelationName', {
                                            rules: [{ required: false, whitespace: true, min: 0, max: 32, message: '关联名长度为0-32' }],
                                        })(
                                            <Input className='addetd-a-r' addonBefore="关联名" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd indtner'>
                                <InputGroup compact>
                                    <Input addonBefore="状 态" />
                                    <Select value={this.state.relationstatus} onChange={this.relationstatusChange.bind(this)} placeholder='请选择'>
                                        <Option value="1">已启用</Option>
                                        <Option value="0">已禁用</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            {/* <FormItem> */}
                            <Button type="primary" className='member-button' icon="search" onClick={this.searchBtn.bind(this)}>搜索</Button>
                            {/* </FormItem> */}
                            <Button type="primary" className='member-button' icon="reload" onClick={this.resetBtn.bind(this)}>重置</Button>
                            <div className='goods-label-tabletr' style={{ float: 'right' }}>
                                <Link to="/relationdetail/0"><Button className='goods-label-table-app' icon="plus">新增</Button></Link>
                            </div>
                        </div>
                        <div className='goods-label-table clearfix'>
                            <Table
                                columns={columns}
                                dataSource={dataList}
                                pagination={false}
                                bordered
                            />
                            <div className='showmodele'>
                                <Modal title={this.state.OperationStatus == "0" ? "启用" : "关闭"} wrapClassName="vertical-center-modal" visible={this.state.Closevisible}
                                    onOk={this.ClosehandleOk.bind(this, this.state.OperationRelationID, this.state.OperationStatus, this.state.OperationRelationName)} onCancel={this.ClosehandleCancel.bind(this)}
                                    width={342}
                                    footer={null}
                                >
                                    <p className='showp'>您确定{this.state.OperationStatus == "0" ? "启用" : "关闭"}<i>{this.state.OperationRelationName}</i>关联</p>
                                    <p className='showp-a'><Button type="primary" onClick={this.ClosehandleOk.bind(this, this.state.OperationRelationID, this.state.OperationStatus, this.state.OperationRelationName)} className='member-button member-button-a'> 确 定</Button></p>
                                </Modal>
                            </div>
                            <div className='showmodele'>
                                <Modal title="删除" wrapClassName="vertical-center-modal" visible={this.state.ClosevisibleDel}
                                    onOk={this.ClosehandleDelOk.bind(this, this.state.OperationRelationID)} onCancel={this.ClosehandleDelCancel.bind(this)}
                                    width={342}
                                    footer={null}
                                >
                                    <p className='showp'>确认删除该关联名？</p>
                                    <p className='showp-a'><Button type="primary" onClick={this.ClosehandleDelOk.bind(this, this.state.OperationRelationID)} className='member-button member-button-a'> 确 定</Button></p>
                                </Modal>
                            </div>
                        </div>
                        <div className='goods-label-let'>
                            <div className="floor-ppagi">
                                <p className="floor-ppagip">
                                    当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.relationcount ? this.state.pagesize * this.state.pageindex : this.state.relationcount}条记录，
                                    共{this.state.relationcount}条记录
                                </p>
                                <Pagination current={this.state.pageindex} total={this.state.relationcount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                            </div>
                        </div>
                    </div>
                </div>
            </Form>
        )
    }
}

const Goodsrelevance = Form.create()(RegForm);
export default Goodsrelevance;